require([
  'jquery',
  'pageInit',
  'dataTableFilter',
  'loading',
  'bootstrap-dialog',
  'notification',
  'listAsyncOp'
], function($, vamakerPage, VamDataTable, VamLoader, BootstrapDialog, VamOpMsg, VamListOp) {
  $(function() {
    var 
      $dataTable = $('#data-table'),
      dataUrl = VAM.getVar('CREATIVE_DATA_LIST'),
      dataStrategyOp = VAM.getVar('STRATEGY_LIST_URL'),
      // dataLinkOp = VAM.getVar('LIST_LINK_OP_URL'),
      dataUnlinkOp = VAM.getVar('LIST_UNLINK_OP_URL'),
      isAllBrand = VAM.getVar('IS_ALL_BRAND'),
      $reportDataThead = $dataTable.find('thead'),
      $loadingWrap = new VamLoader().loader($('#list-loading-wrap')),
      listTable, tableOptions = {},
      strategyListRender;

    $('.new-operate-btn').on('click', function(evt){
      if (isAllBrand) {
        evt.preventDefault();
        $('#all_tip').removeClass('hidden');
      }
    });
    
    // Sub list render.
    strategyListRender = function (data) {
      var resultStr = '',
        subArr = data;
      if (subArr.length === 0) {
        resultStr = '<tr><td colspan="7"><p class="text-center">' + VAM.j('The data in the table is empty') + '</p></td></tr>';
      } else {
        for (var i = 0; i < subArr.length; i++) {
          var subStr = '<tr>'
                     + '<td><p title="' + subArr[i].id + '">' + subArr[i].id +'</p></td>'
                     + '<td><p title="' + subArr[i].name + '">' + subArr[i].name +'</td>'
                     + '<td><p title="' + subArr[i].launch + '">' + subArr[i].launch + '</td>' 
                     + '<td><p title="' + subArr[i].status + '">' + subArr[i].status + '</td>'
                     + '<td><p title="' + subArr[i].launchTime + '">' + subArr[i].launchTime + '</td>'
                     + '<td><p title="' + subArr[i].modifiedDate + '">' + subArr[i].modifiedDate + '</td>'
                     + '<td><div class="tab-btn-group">'
                     + '<button class="btn btn-warning btn-xs tab-unlink" data-type="unlink" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i>" data-id="' + subArr[i].id + '" type="button" title="' + VAM.j('unbind') + '"><i class="fa fa-unlink"></i></button>'
                     + '</div></td>'
                     + '</tr>';
          resultStr += subStr;
        }
      };
      resultStr = '<table cellpadding="0" cellspacing="0" border="0" class="table table-hover table-bordered" style="margin-bottom:0;border: 1px solid #ddd;">'
                + '<thead>'
                + '<tr><th title="ID">ID</th><th title="' + VAM.j('Solution Name') + '">' + VAM.j('Solution Name') + '</th><th title="' + VAM.j('Campaign') + '">' 
                + VAM.j('Campaign') + '</th><th title="' + VAM.j('Status') + '">' + VAM.j('Status') + '</th><th title="' + VAM.j('Campaign Time') + '">' + VAM.j('Campaign Time') + '</th><th title="' + VAM.j('Update Time') + '">' + VAM.j('Update Time') + '</th><th class="tab-op" title="' + VAM.j('Operate') + '">' + VAM.j('Operate') + '</th></tr>'
                + '</thead>'
                + '<tbody>'
                + resultStr
                + '</tbody></table>';
      return resultStr;
    };
    // Table settings.
    tableOptions = {
      'ajax': {
        'url': dataUrl
      },
      'order': [12,'desc'],
      'columns': [
        {'data': 'id'},
        {'data': 'name'},
        {'data': 'strategy'},
        {'data': 'status'},
        // {'data': 'creativeType'},
        {'data': 'materialType'},
        {'data': 'creativeSize'},
        {'data': 'vocation'},
        {'data': 'cost'},
        {'data': 'showCount'},
        {'data': 'clickCount'},
        {'data': 'clickRate'},
        // {'data': 'cpm'},
        {'data': 'cpc'},
        {'data': 'modifiedDate'},
        {'data': 'operate'}
      ],
      'columnDefs': [
        {
          'targets': [0,1,5,8,9,12],
          'render': function (data, type, full, meta) {
            return '<p title="' + data + '">' + data + '</p>'
          }
        },
        {
          'targets': 2,
          'render': function (data, type, full, meta) {
            return '<p title="' + VAM.j('Unfolded view solution') + '"><button title="' + VAM.j('Unfolded view solution') + '" class="btn btn-info btn-xs tab-strategy-list" data-type="strategy" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i> ' + VAM.j('loading') + '..." data-id="' + full.id + '"><i class="fa fa-puzzle-piece"></i>' + VAM.j('View Solution') + '</button></p>'
          }
        },
        {
          'targets': 3,
          'render': function (data, type, full, meta) {
            var result = '';
            if (data === 'to-be-audit' && full.creativeType !== 'video') {
              result = VAM.j('Normal');
              //result = '待审核';
            } else if (data === 'to-be-audit' && full.creativeType === 'video') {
              result = VAM.j('Pending');
            } else if (data === 'auditing') {
              result = VAM.j('Auditing');
            } else if (data === 'passed') {
              result = VAM.j('Passed');
            } else if (data === 'refused') {
              result = VAM.j('Refused');
            } else if (data === 'paused') {
              result = VAM.j('Paused');
            } else if (data === 'no-owner') {
              result = VAM.j('No Owner');
            } else if (data === 'unfinished') {
              result =VAM.j('Incomplete');
            };
            return '<p title="' + result + '">' + result +'</p>';
          }
        },
        // {
        //   'targets': 4,
        //   'render': function (data, type, full, meta) {
        //     var result = '', more = '';
        //     if (full.custom === '1') {
        //       data = data + '(自定义)';
        //     }
        //     return '<p title="' + data + '">' + data +'</p>';
        //   }
        // },
        {
          'targets': 4,
          'render': function (data, type, full, meta) {
            var result = '', more = '';
            if (data === 'static-pic') {
              result = VAM.j('Static Pic');
            } else if (data === 'dynamic-pic') {
              result = VAM.j('Dynamic Pic');
            } else if (data === 'swf') {
              result = 'SWF';
            } else if (data === 'txt') {
              result = VAM.j('Text Chain');
            // } else if (data === 'swf' && full.creativeType === 'app') {
            //   result = 'SWF';
            } else if (data === 'flv') {
              result = 'FLV';
            } else if (data === 'mp4') {
              result = 'MP4';
            } else if (data === 'ogg') {
              result = 'OGG';
            } else if (data === 'webm') {
              result = 'WebM';
            }
            if (full.creativeType === 'video' || full.creativeType === 'mobile-video') {
              more = '<p title="' + full.duration + '">' + VAM.j('Duration') + '：' + full.duration +'s</p>';
            } else if (full.creativeType === 'cpe') {
              var cpeVideoType = full.cpeMaterialType.split(','),
                  videoType = [], meType = '';
              for (var i = 0; i < cpeVideoType.length; i++) {
                if (cpeVideoType[i] === 'mp4') {
                  meType = 'MP4';
                } else if (cpeVideoType[i] === 'ogg' || cpeVideoType[i] === 'ogv') {
                  meType = 'OGV';
                } else if (cpeVideoType[i] === 'webm') {
                  meType = 'WebM';
                } else if(cpeVideoType[i] === 'flv'){
                  meType = 'FLV';
                };
                videoType.push(meType);
              };
              videoType = videoType.join(',');
              more = '<p title="' + full.cpeMaterialType+ '">' + videoType +'</p>';
            }
            return '<p title="' + result + '">' + result +'</p>' + more;
          }
        },
        {
          'targets': [8,9],
          'visible': VAM.getVar('CLICK_FILTER_STATUS'),
          'orderable': false,
          'render': function (data, type, full, meta) {              
            var check = data === "open" ? "checked" : "",
              resultStr;
            resultStr = '<p title="' + data + '">' + data +'</p>';
            return resultStr;
          }
        },
        {
          'targets': 6,
          'render': function (data, type, full, meta) {
            var result = '', record = '', item;
            for (var i = 0, len = data.length; i < len; i++) {
              item = data[i];
              record = '<p class="text-success"><span class="label label-default">' + item['channel'] + '</span> ' + item['tags'] + '</p>';
              result += record;
            };
            return result;
          }
        },
        {
          'targets': 7,
          'render': function (data, type, full, meta) {
            return '<p class="text-success" title="' + data + '"><i class="fa fa-rmb"></i> ' + data + '</p>';
          }
        },
        {
          'targets': [-3,-4],
          'visible': VAM.getVar('CLICK_FILTER_STATUS'),
          'orderable': false,
          'render': function (data, type, full, meta) {
            return '<p class="text-success" title="' + data + '"><i class="fa fa-rmb"></i> ' + data + '</p>';
          }
        },
        {
          'targets': 10,
          'visible': VAM.getVar('CLICK_FILTER_STATUS'),
          'orderable': false,
          'render': function (data, type, full, meta) {
            return '<p class="text-default" title="' + data + '">' + data + ' %</p>';
          }
        },
        {
          'targets': -1,
          'render': function (data, type, full, meta) {
            var pausedStopStr = '',linkUnlinkStr = '', editUrl = '';
            if (full.status === 'to-be-audit' || full.status === 'passed') {
              // launch could pause.
              pausedStopStr = '<button class="btn btn-danger btn-xs tab-pasue" data-type="pause" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i>" title="' + VAM.j('Pause') + '"><i class="fa fa-pause"></i></button>';
            } else if (full.status === 'paused') {
              // launch could resume.
              pausedStopStr = '<button class="btn btn-success btn-xs tab-resume" data-type="resume" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i>" title="' + VAM.j('Resume') + '"><i class="fa fa-play-circle-o"></i></button>';
            };
            // if (full.strategy === '' || full.strategy === 'no-owner') {
            //  linkUnlinkStr = '<button class="btn btn-success btn-xs tab-link" data-type="link" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i>" title="绑定策略"><i class="fa fa-link"></i></button>';
            // } else {
            //  linkUnlinkStr = '<button class="btn btn-warning btn-xs tab-unlink" data-type="unlink" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i>" type="button" title="解除绑定"><i class="fa fa-unlink"></i></button>';
            // };
            if (full.creativeType === 'mobile-web') {
              editUrl = VAM.getVar('DATA_WEB_EDIT_URL');
            } else if (full.creativeType === 'mobile-app') {
              editUrl = VAM.getVar('DATA_APP_EDIT_URL');
            } else if (full.creativeType === 'banner') {
              editUrl = VAM.getVar('DATA_BANNER_EDIT_URL');
            } else if (full.creativeType === 'mobile-video') {
              editUrl = VAM.getVar('DATA_MOBILE_VIDEO_EDIT_URL');
            } else if (full.creativeType === 'video'){
              editUrl = VAM.getVar('DATA_VIDEO_EDIT_URL');
            } else {
              editUrl = VAM.getVar('DATA_CPE_EDIT_URL');
            };
            if (full.custom === '1') {
              editUrl = VAM.getVar('DATA_CUSTOM_EDIT_URL');
            }
            return '<div class="tab-btn-group">'
                  + '<input class="row-info" type="hidden" value="' + full.id + '">'
                  + '<a href="' + editUrl + '?id=' + full.id + '" class="btn btn-primary btn-xs tab-edit" data-loading-text="' + VAM.j('loading') + '..." title="' + VAM.j('Edit') + '"><i class="fa fa-edit"></i></a>'
                  // + pausedStopStr
                  // + linkUnlinkStr
                  // + '<button class="btn btn-info btn-xs tab-report" data-loading-text="加载中..." title="报表"><i class="fa fa-file-text"></i></button>'
                  + '<button class="btn btn-success btn-xs tab-preview" data-type="preview" data-role="' + full.creativeType + '" data-custom="' + full.custom + '" data-loading-text="' + VAM.j('loading') + '..." type="button" title="' + VAM.j('Creative Preview') + '"><i class="fa fa-eye"></i></button>'
                  + '</div>';
          }
        }
      ],
      'vamSettings': {
        'vamColumnFilter': false,
      },
      'initComplete': function() {
        tableResize = new VamDataTable().columnResize($dataTable);
      }
    };
    $dataTable
    .on('preXhr.dt', function(evt) {
      $loadingWrap.show();
    });
    listTable = new VamDataTable().dataTables($dataTable, tableOptions);
    // After table data list.
    listTable.on('xhr.dt', function(evt) {
      $loadingWrap.fadeOut();
    });
    
    $dataTable.on('click', 'tbody td .tab-preview', function(evt) {
      var $me = $(this),
      $rowInfo = $me.siblings('.row-info'),
      opId = $rowInfo.val(),
      opType = $me.data('type'),
      opRole = $me.data('role'),
      opCustom = $me.data('custom'),
      opData, creativeIfrUrl,
      previewOpUrl;
      evt.preventDefault();
      if (opRole === 'mobile-web') {
        previewOpUrl = VAM.getVar('LIST_PREVIEW_WEB_OP_URL');
      } else if (opRole === 'mobile-app'){
        previewOpUrl = VAM.getVar('LIST_PREVIEW_APP_OP_URL');
      } else if (opRole === 'banner') {
        previewOpUrl = VAM.getVar('LIST_PREVIEW_BANNER_OP_URL');
      } else if (opRole === 'video'){
        previewOpUrl = VAM.getVar('LIST_PREVIEW_VIDEO_OP_URL');
      } else if (opRole === 'mobile-video') {
        previewOpUrl = VAM.getVar('LIST_PREVIEW_MOBILE_VIDEO_OP_URL');
      } else if (opRole === 'cpe') {
        previewOpUrl = VAM.getVar('LIST_PREVIEW_CPE_OP_URL');
      }
      // previewOpUrl = opRole === 'mobile-web' ? VAM.getVar('LIST_PREVIEW_WEB_OP_URL') : VAM.getVar('LIST_PREVIEW_APP_OP_URL');
      creativeIfrUrl = previewOpUrl + '?id=' + opId + '&type=' + opRole;
      if (opCustom === '1' || opCustom === 1) {
        creativeIfrUrl += '&custom=' + opCustom; 
      }
      BootstrapDialog.show({
        title: VAM.j('Creative Preview'),
        size: BootstrapDialog.SIZE_WIDE,
        message: $('<iframe id="creative-preview-ifr" frameborder="0" style="width: 100%; min-height: 800px;" src="' + creativeIfrUrl + '"></iframe>'),
        buttons: [{
          label: VAM.j('Close'),
          cssClass: 'btn-default',
          action: function(dialogItself) {
            dialogItself.close();
          }
        }]
      });
    });

    $dataTable.on('click', 'tbody td .tab-strategy-list', function () {
      var $me = $(this),
          opId = $me.data('id'),
          opType = $me.data('type'),
          $icon = $me.find('.fa'),
          tr = $(this).parents('tr'),
          row = listTable.row(tr);
      $icon.toggleClass('fa-minus-circle');
      if (row.child.isShown()) {
        row.child.hide();
        tr.removeClass('shown');
      } else {
        VamListOp.listOp({
          url: dataStrategyOp,
          data: {
            id: opId,
            type: opType
          },
          before: function () {
            $me.button('loading');
          },
          success: function (data) {
            row.child(strategyListRender(data)).show();
            tr.addClass('shown');
          },
          always: function () {
            $me.button('reset');
          }
        });
      }
    });

    $dataTable.on('click', 'tbody td .tab-unlink', function (evt) {
      var $me = $(this),
        opId = $me.data('id'),
        crtId = $($me).parent('div').parent('td').parent('tr').parent('tbody').parent('table').parent('td').parent('tr').prev('tr').children('td:first').children('p:first').html(),
        opType = $me.data('type'),
        opData;
      evt.preventDefault();
      opData = {
        solution_id: opId,
        creative_id: crtId,
        type: opType,
        rnd: (new Date()).getTime()
      };
      BootstrapDialog.confirm({
        title: VAM.j('Unbind Creative'),
        message: VAM.j('Confirm to unbind the creative?'),
        type: BootstrapDialog.TYPE_DANGER,
        closable: true, 
        draggable: true,
        btnCancelLabel: VAM.j('Cancel'),
        btnOKLabel: VAM.j('OK'),
        btnOKClass: 'btn-danger', 
        callback: function(result) {
          if(result) {
            VamListOp.listOp({
              url: dataUnlinkOp,
              data: opData,
              before: function () {
                $me.button('loading');
              },
              success: function (data) {
                if (data.status === 'success') {
                  VamOpMsg.messager(data);
                  listTable.ajax.reload();
                } else {
                  VamOpMsg.messager(data);
                }
              },
              always: function () {
                $me.button('reset');
              }
            });
          }
        }
      });
    });
  });
});
